package com.garbagecode.routetable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.garbagecode.routetable.path.Segment;

public class Route {
  private String path;
  private Object item;
  private int firstPathParameterIndex = -1;
  private List<Segment> segmentList = new ArrayList<Segment>();

  public Route(String path, Object item) {
    this.path = path;
    this.item = item;
  }

  public Route(String path, Object item, int firstPathParameterIndex, List<Segment> segmentList) {
    this.path = path;
    this.item = item;
    this.firstPathParameterIndex = firstPathParameterIndex;
    this.segmentList = segmentList;
  }

  public String getPath() {
    return path;
  }

  public Object getItem() {
    return item;
  }

  public int getFirstPathParameterIndex() {
    return firstPathParameterIndex;
  }

  public List<Segment> getSegmentList() {
    return segmentList;
  }

  /**
   * 返回路径 path 中的路径参数
   * 比如：
   * 这里假设路由表里有条路由 "/hello/:who"
   * getPathParameterMap("/hello/world"); // => { "who" : "world" }
   * 
   * @param path
   * @return
   */
  public Map<String, String> getPathParameterMap(String path) {
    if (path == null) {
      throw new IllegalArgumentException("path null");
    }

    Map<String, String> pathParameterMap = new HashMap<String, String>();
    String[] pathSegments = null;

    if (firstPathParameterIndex < 0 || firstPathParameterIndex > path.length()) {
      return pathParameterMap;
    }
    
    if (firstPathParameterIndex == path.length()) {
      pathSegments = new String[] { "" };
    } else {
      pathSegments = path.substring(firstPathParameterIndex).split("/", -1);
    }

    Segment segment = null;

    // 依次计算路径参数的值
    for (int i = 0; i < pathSegments.length && i < segmentList.size(); i++) {
      segment = segmentList.get(i);

      if (segment.getType() == Segment.TYPE_PARAMETER) {
        pathParameterMap.put(segment.getName(), pathSegments[i]);
      }
    }

    return pathParameterMap;
  }

}
